import { HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';

@Injectable({
  providedIn: 'root'
})
export class MessageService {

  constructor(
    private message: NzMessageService,
    private modal: NzModalService
  ) { }

  success(content: string, isRemove: boolean = false){
    if(isRemove){
      this.message.remove()
    }
    this.message.success(content)
  }
  error(content: string, isRemove: boolean = false){
    if(isRemove){
      this.message.remove()
    }
    this.message.error(content)
  }
  info(content: string, isRemove: boolean = false){
    if(isRemove){
      this.message.remove()
    }
    this.message.info(content)
  }

  successModal(
    title: string = '', 
    onOk: any = null,
    content: string = ''
  ){
    this.modal.success({
      nzTitle: title,
      nzContent: content,
      nzOnOk: () => {
        if(onOk){
          onOk()
        }
      },
      nzClosable: false
    })
  }
  confirmModal(
    title: string = '', 
    onOk: any = null,
    onCancel: any = null,
    content: string = ''
    ){
    this.modal.confirm({
      nzTitle: title,
      nzContent: content,
      nzOnOk: () => {
        if(onOk){
          onOk()
        }
      },
      nzOnCancel: () => {
        if(onCancel){
          onCancel()
        }
      }
    })
  }

  infoModal(
    title: string = '', 
    onOk: any = null,
    content: string = ''
    ){
    this.modal.info({
      nzTitle: title,
      nzContent: content,
      nzOnOk: () => {
        if(onOk){
          onOk()
        }
      }
    })
  }

  createErrorMessage(error: HttpErrorResponse | null = null, message = ''){
    if(error){
      console.log(error)
      this.error(error.error.Message)
      return
    }
    if(message){
      this.error(message)
      return
    }
    this.error('操作失败, 请稍后再试')
  }
}
